import os
import django
import sys
from datetime import datetime

sys.path.insert(0, "./")

os.environ.setdefault('DJANGO_SETTINGS_MODULE','fund.settings')

django.setup()

from fundinfo.models import *
from analysis.price_analysis import PriceAnalysis
from trading.models import *
from tools.add_data import *

# 将"2025/9/8", "9:1"这种格式的时间转为"2025-10-08", "09：01：00“
def fix_time(date, time):
    date = date.split("/")
    time = time.split(":")
    return date[0] + "-" + date[1].zfill(2) + "-" + date[2].zfill(2) , time[0].zfill(2) + ":" + time[1].zfill(2) + ":" + "00"

def read_fund_price(code):
    price = PriceAnalysis(code)
    price.setPriceDir("../data/")
    price.readPriceData()
    data = price.price
    return data

def getFundCodeByName(name):
    fund = FundName.objects.filter(name=name)   
    if fund.exists():
        return fund[0].code
    else:
        return ""

# 查询交易费用
def get_trading_cost(code, is_buy):
    fund = FundName.objects.filter(code=code)
    if fund == None and len(fund) == 0:
        return 0.00
    print("rate:", fund[0].purchaseRate, fund[0].sellingRate)

    if is_buy:
        return fund[0].purchaseRate * 0.01
    else:
        return fund[0].sellingRate * 0.01

# 根据交易金额和时间计算交易的份额和时间
# 输入：交易资金，交易日期，交易时间，基金编码
# 输出：可购买的基金份额，基金净值
def get_unit_can_buy(amount, is_buy, day, tm, code):
    print(amount, is_buy, day, tm, code)
    data = read_fund_price(code)
    cost_rate =get_trading_cost(code, is_buy)
    nextday = False
    jjjz = 0.0
    info = None
    if tm > "15:00:00":
        nextday = True
        print("nextday")
    else:
        print("<=")
    d = datetime.strptime(day, "%Y-%m-%d").date
    lastday = ""
    for item in data:
        date_str = item.date.strftime("%Y-%m-%d")
        if nextday:
            if day < date_str:
                print("date_str2=", date_str)
                jjjz = item.jjjz
                info = item
                break
        else:
            if day <= date_str:
                print("date_str=", date_str, lastday)
                jjjz = item.jjjz
                info = item
                break
        lastday = date_str
    #print("jjjz:", jjjz, info.date)
    
    #print("cost_rate=", cost_rate)
    #买入的计算公式：
    #units*jjjz*(1+0.0015) = amount
    #卖出的计算公式：
    #units*jjjz*(1-0.0025) = amount 
    units = amount / (1+cost_rate) / info.jjjz
    if is_buy == False: 
        units = amount / (1-cost_rate) / info.jjjz

    units = round(units,2)

    #print("units=", round(units,2))
    cost = amount - units*info.jjjz
    #print("cost=", round(cost,2))
    #print(units, jjjz, info.date)
    if is_buy:
        return units, jjjz, info.date
    else:
        return -units, jjjz, info.date

# 读取数据
# 买入	10000.00	2025-10-31 21:59:09	交易进行中
# 卖出	20677.99	2025-10-29 16:22:53	正常
def ant_read_data(code, filename):
    fp = open(filename)
    for line in fp:
        items = line.strip().split()
        if len(items) < 5:
            continue

        day = items[0]
        tm = items[1]
        amount = float(items[2])
        result = items[4]
        action = items[3]
        print(day, tm, amount, result, action)

        if result != "成功":
            print("--------Not Process1--------", line)
            continue

        is_buy = False
        if action == "买入" or action == "转换转入" or action == "定投":
            is_buy = True
        elif action == "卖出" or action == "转换转出":
            is_buy = False
        else:
            print("--------Not Process2--------", line)
            continue
        
        #code = getFundCodeByName(fundName)
        #day, tm = fix_time(items[0], items[1])


        
        units, jjjz, day = get_unit_can_buy(amount, is_buy, day, tm, code)

        if is_buy == False:
            amount = -amount

        print("to save:", units, jjjz, day)

        save_fund_info(code, day, amount, units)
    fp.close()
    return


'''
print(fix_time("2025/1/8", "15:2"))
print(getFundCodeByName("招商量化精选股票A"))
print(getFundCodeByName("天弘沪深300ETF联接C"))
print(getFundCodeByName("景顺长城中证沪港深红利成长低波动指数E"))

 
print(get_unit_can_buy(20677.99, False, "2025-10-29", "16:32:00", "005918"))
print(get_unit_can_buy(20112.43, False, "2025-08-19", "22:01:01", "260112"))

#get_unit_can_buy(2000, "2025-09-05", "15:26:00", "001917")
#get_unit_can_buy(2000, "2025-08-31", "03:26:00", "001917")
'''

ant_read_data("021313", "tools/ant_data.txt")